package kode.boot.file.api;

import kode.base.core.util.CollectionUtil;
import kode.base.core.util.StringUtil;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.List;

/**
 * AbstractFileValidator
 *
 * @author Stark
 * @date 2019/1/4
 */
@Getter
@Setter
@NoArgsConstructor
public abstract class AbstractFileValidator implements FileValidator {

	private boolean parseAsImage;
	private String message = "File validation fail";

	public AbstractFileValidator(boolean parseAsImage) {
		this.parseAsImage = parseAsImage;
	}

	public AbstractFileValidator(String message) {
		this.message = message;
	}

	public AbstractFileValidator(boolean parseAsImage, String message) {
		this.parseAsImage = parseAsImage;
		this.message = message;
	}

	@Override
	public boolean parseAsImage() {
		return parseAsImage;
	}

	public void validateWidth(FileMetadata<?> fileMetadata, Integer min, Integer max) {
		if (min == null && max == null) {
			throw new IllegalArgumentException("min/max of width must not be both none");
		}

		if (fileMetadata.getWidth() == null || !fileMetadata.containsProperty("width")) {
			throw new FileValidateException("Only image files could be validated width");
		}

		Integer width = fileMetadata.getWidth() != null ? fileMetadata.getWidth() : (Integer) fileMetadata.getProperty("width");
		if ((min != null && min > width)
				|| (max != null && max < width)) {
			throw new FileValidateException(message);
		}
	}

	public void validateHeight(FileMetadata<?> fileMetadata, Integer min, Integer max) {
		if (min == null && max == null) {
			throw new IllegalArgumentException("min/max of height must not be both none");
		}

		if (fileMetadata.getHeight() == null || !fileMetadata.containsProperty("height")) {
			throw new FileValidateException("Only image files could be validated height");
		}

		Integer height = fileMetadata.getHeight() != null ? fileMetadata.getHeight() : (Integer) fileMetadata.getProperty("height");
		if ((min != null && min > height)
				|| (max != null && max < height)) {
			throw new FileValidateException(message);
		}
	}

	public void validateSize(FileMetadata<?> fileMetadata, Long size) {
		if (fileMetadata.getSize() > size) {
			throw new FileValidateException(message);
		}
	}

	public void validateExtension(FileMetadata<?> fileMetadata, List<String> extList) {
		if (StringUtil.isEmpty(fileMetadata.getExtension())
				|| !StringUtil.equalsAnyIgnoreCase(fileMetadata.getExtension(), CollectionUtil.toArray(extList, String.class))) {
			throw new FileValidateException(message);
		}
	}
}
